var CertProxy = require('../../proxy/cert.js');
//var CertModel    = require('../../models/certificates.js');
var multiparty = require('multiparty');
var fs = require("fs");
var path = require('path');
var config = require('../../config.json');
var logger = require('log4js').getLogger();
var EventProxy = require('eventproxy');
var ProjectProxy    = require('../../proxy/project.js');
var _            = require('lodash');


exports.updateCert = function (req, res, next) {
    var cert_id = req.params.cert_id;
    var targetDir = config.cert_repo;
    var form = new multiparty.Form({
        uploadDir: targetDir
    });
    var cert_info = {};
    var cert_files = {};

    try {
        fs.accessSync(targetDir, fs.R_OK);
    } catch (e) {
        fs.mkdirSync(targetDir);
    }

    var ep = new EventProxy();
    ep.fail(function (err) {
        return res.format_json(null, 500, err);
    });

    form.parse(req, function (err, fields, files) {
        if (err) {
            logger.error(err);
            return res.format_json(null, 500, err);
        }
        else {
            cert_info['name'] = fields['CertName'][0];
            cert_info['type'] = fields['Type'][0];
            var extend_info = {};
            switch (fields['Type'][0]) {
                case "IOS":
                {
                    var num = 2;
                    extend_info["provisionID"] = fields["provisionID"][0];
                    extend_info["P12Password"] = fields["P12Password"][0];
                    cert_info['extend_info'] = extend_info;
                    cert_info['files'] = {};
                    ep.after('get_cert_info', num, function () {
                        CertProxy.updateCert(cert_id, cert_info, function (err, data) {
                            if (err) {
                                return res.format_json(null, 500, "更新证书失败:" + err);
                            }
                            res.format_json(data);
                        });
                    });
                    if (files["P12File"] && files["P12File"].length > 0) {
                        var P12File = files["P12File"][0];
                        var P12Path = P12File.path;
                        var P12Path_dstPath = path.join(targetDir, P12File.originalFilename);
                        fs.rename(P12Path, P12Path_dstPath, function (err) {
                            if (err) {
                                logger.error(err);
                                return res.format_json(null, 500, err);
                            }
                            else {
                                cert_files["P12File"] = {"file_name": P12File.originalFilename, "file_path": P12Path_dstPath};
                                cert_info['files'].P12File = cert_files["P12File"];
                                ep.emit('get_cert_info');
                            }
                        });
                    }else{
                        ep.emit('get_cert_info');
                    }
                    if (files["provisionFile"] && files["provisionFile"].length > 0) {
                        var provisionFile = files["provisionFile"][0];
                        var provisionFilePath = provisionFile.path;
                        var dstPath_provisionFile = path.join(targetDir, provisionFile.originalFilename);
                        fs.rename(provisionFilePath, dstPath_provisionFile, function (err) {
                            if (err) {
                                logger.error(err);
                                return res.format_json(null, 500, err);
                            }
                            else {
                                cert_files["provisionFile"] = {
                                    "file_name": provisionFile.originalFilename,
                                    "file_path": dstPath_provisionFile
                                };
                                cert_info['files'].provisionFile = cert_files["provisionFile"];
                                ep.emit('get_cert_info');
                            }
                        });
                    }else{
                        ep.emit('get_cert_info');
                    }
                    break;
                }
                case "Android":
                {
                    var count = 1;
                    extend_info["KeyStoreSecret"] = fields["KeyStoreSecret"][0];
                    cert_info['extend_info'] = extend_info;
                    ep.after('get_cert_info', count, function () {
                        CertProxy.updateCert(cert_id, cert_info, function (err, data) {
                            if (err) {
                                return res.format_json(null, 500, "更新证书失败:" + err);
                            }
                            res.format_json(data);
                        });
                    });
                    if (files["keyStoreFile"] && files["keyStoreFile"].length > 0) {
                        var keyStoreFile = files["keyStoreFile"][0];
                        var keyStoreFilePath = keyStoreFile.path;
                        dstPath = path.join(targetDir, keyStoreFile.originalFilename);
                        fs.rename(keyStoreFilePath, dstPath, function (err) {
                            if (err) {
                                logger.error(err);
                                return res.format_json(null, 500, err);
                            }
                            else {
                                cert_files["keystoreFile"] = {
                                    "file_name": keyStoreFile.originalFilename,
                                    "file_path": dstPath
                                };
                                cert_info['files'] = cert_files;
                                ep.emit('get_cert_info');
                            }
                        });
                    }else{
                        ep.emit('get_cert_info');
                    }
                    break;
                }
            }

        }
    });

};

exports.removeCert = function (req, res, next) {
    cert_id = req.params.cert_id;
    CertProxy.removeCert(cert_id, function (err, data) {
        if (err) {
            return res.format_json(null, 500, "删除证书失败:" + err);
        }
        res.format_json(data);
    });
};

exports.getCert = function (req, res, next) {
    var cert_id = req.params.cert_id;
    CertProxy.getCert(cert_id, function (err, data) {
        if (err) {
            return res.format_json(null, 500, "获取证书失败:" + err);
        }
        res.format_json(data);
    });
};


exports.getCerts = function (req, res, next) {
    var project_id = req.params.project_id;
    var ep = new EventProxy();

    ep.fail(function(err){
        res.format_json(null,500,err);
    });
    ProjectProxy.getProjectById(project_id,ep.done('certs_in_project'));
    ep.on('certs_in_project', function(project) {
        CertProxy.getCerts(function (err, data) {
            if (err) {
                return res.format_json(null, 500, "获取证书失败:" + err);
            }
            var certs = [];
            data.map(function(item){
                project.certs.map(function(cert_id){

                    if(item._id.toString() == cert_id.toString()){
                        certs.push(item);
                    }
                });

            });
            console.log(certs);
            res.format_json(certs, 0);
        });
    });
};

//exports.updateCert = function (req, res, next) {
//var body = req.body;
//var cert_id = body.cert_id;
//var cert_info = {
//    name: body.name,
//    files: body.files,
//    extend_info: body.extend_info
//};
//CertProxy.updateCert(cert_id, cert_info, function (err, data) {
//    if (err) {
//        return res.format_json(null, 500, "更新证书信息失败:" + err);
//    }
//    res.format_json(data);
//});
//};

exports.addCert = function (req, res, next) {
    var cert_info = req.body;
    var project_id = req.params.project_id;

    var ep = new EventProxy();
    ep.fail(function(err){
        res.format_json(null,500,err);
    });

    CertProxy.addCert(cert_info, ep.done('cert_added'));

    ep.on('cert_added', function(cert){
        ProjectProxy.pushProCert(project_id,cert._id, ep.done('cert_pushed'));
        ep.on('cert_pushed', function(member){
            res.format_json({success:true,cert:cert});
        });
    });


};